package com.aaa.security;

import com.aaa.entity.Emp;
import com.aaa.entity.Permission;
import com.aaa.entity.Role;
import com.aaa.service.EmpService;
import com.aaa.service.PermissionService;
import com.aaa.service.RoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;

/**
 * 获取用户信息
 */
@Repository
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    EmpService empService;
    @Resource
    RoleService roleService;
    @Resource
    PermissionService permissionService;

    /**
     * 根据用户名获取用户信息
     * @param s :表单提交的用户名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        QueryWrapper<Emp> empQueryWrapper = new QueryWrapper<>();
        empQueryWrapper.eq("eusername",s);
        List<Emp> list = empService.list(empQueryWrapper);
        if(list.size() == 1){
            Emp emp=list.get(0);
            //查询用户得角色
            Role role=roleService.getById(emp.getRoleid());
            //获取角色id
            Integer rid = role.getRid();
            //查询角色拥有有的权限
            QueryWrapper<Permission> queryWrapper=new QueryWrapper<Permission>();
             queryWrapper.eq("rid", rid);
           List<Permission> permissions=permissionService.list(queryWrapper);
            System.out.println("listsize"+list.size());
            StringBuffer str=new StringBuffer();//直接写死了
            for (int i=0;i<permissions.size();i++){
                System.out.println(permissions.get(i).getPname());
                str.append(permissions.get(i).getPname());
            }
           // str.append(role.getRolename());
            //设置权限
      /*    if(s.equals("yyx")){
                //将字符串按照逗号分隔，转换为权限列表
                //ROLE_角色,add,update,select 权限
                str.append("ROLE_ADMIN");
            }else {
                str.append("ROLE_TEST");
            }*/
            //给用户设置权限
            emp.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList(str.toString()));
          //  System.out.println(list);
            return list.get(0);
        }else{
            new UsernameNotFoundException("用户名不存在");
            return null;
        }
    }


}
